import find_mxnet
import mxnet as mx
import logging
import numpy as np
import os
# Note: The decoded image should be in BGR channel (opencv output)
# For RGB output such as from skimage, we need to convert it to BGR
# WRONG channel will lead to WRONG result
from skimage import io, transform
import web

urls=(
	'/classify/(.*)','get_result'
)
app = web.application(urls,globals())


logger = logging.getLogger()
logger.setLevel(logging.DEBUG)

prefix = "lenet"
num_round = 20
model = mx.model.FeedForward.load(prefix, num_round, ctx=mx.cpu(), numpy_batch_size=1)
mean_img = mx.nd.load("/home/wsy/mxnetMount/example/HCL2000/32data/mean.bin")["mean_img"]

synset = [l.strip() for l in open('synset2.txt').readlines()]
batch_size=1
data_shape = (1, 32, 32)


def PreprocessImage(path, show_img=False):
    # load image
    img = io.imread(path)
    # we crop image from center
    short_egde = min(img.shape[:2])
    yy = int((img.shape[0] - short_egde) / 2)
    xx = int((img.shape[1] - short_egde) / 2)
    crop_img = img[yy : yy + short_egde, xx : xx + short_egde]
    # resize
    #resized_img = transform.resize(crop_img, (32, 32))
    resized_img = crop_img[:,:,0]
    resized_img = transform.resize(resized_img, (32, 32))
    if show_img:
        io.imshow(resized_img)
    # convert to numpy.ndarray
    sample = np.asarray(resized_img) * 256
    # swap axes to make image from (224, 224, 4) to (3, 224, 224)
   #sample = np.swapaxes(sample, 0, 2)
    #sample = np.swapaxes(sample, 1, 2)
    # sub mean
    normed_img = sample - mean_img.asnumpy()
    normed_img.resize(1, 32, 32)
    normed_img=normed_img.reshape(1,1, 32, 32)
    return normed_img

class get_result:
    def GET(self,path):
        print path
        batch = PreprocessImage(path+'.jpg', True)
        prediction = model.predict(batch)[0]
        # print prediction.size #3755
        print prediction.argmax()
        label = synset[prediction.argmax()]
        print 'the result is ' + str(label) + ' and the probability is %f' % prediction.max()

        web.header('Content-Type', 'text/json; charset=utf-8', unique=True)
        return 'the result is ' + str(label) + ' and the probability is %f' % prediction.max()
        # print str(prediction[label])
        #print prediction.max()
        # print str(prediction[label])


if __name__ == '__main__':
    app.run()



"""
datadir = "/home/spark/300hcl"
subdir=os.listdir(datadir)
for sub in subdir:
    if os.path.isdir(datadir+'/'+sub):
        batch = PreprocessImage(datadir+'/'+sub+'/'+'hh001.jpg', True)
        prediction = model.predict(batch)[0]
        print sub+'     '+str(prediction.argmax())

"""